<template>
  <view class="container" :style="{ paddingBottom: safeAreaBottom + 'px' }">
    <!-- 顶部提示栏 -->
    <view class="tip-bar">
      <text class="tip-text">用于微信支付、零钱提现等服务</text>
    </view>

    <!-- 银行卡列表：适配左滑删除的滚动容器 + 加载/空列表提示 -->
    <view class="card-list">
      <!-- 1. 列表加载中提示（原生CSS动画替代uni-icons） -->
      <view class="list-loading" v-if="listLoading">
        <!-- 原生加载动画：旋转圆圈 -->
        <view class="loading-spinner"></view>
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 2. 空列表提示（无银行卡时显示） -->
      <view class="empty-list" v-else-if="cardList.length === 0">
        <text class="empty-text">暂无绑定的银行卡</text>
        <view class="empty-btn" @click="navigateToAddCard">添加银行卡</view>
      </view>

      <!-- 3. 银行卡列表（有数据时显示） -->
      <view
        class="swipe-container"
        v-else
        v-for="(card, index) in cardList"
        :key="card.id"
        :style="{ height: cardItemHeight + 'rpx' }">
        <!-- 左滑删除按钮：加载中禁用 -->
        <view
          class="delete-btn"
          @click.stop="handleDelete(index)"
          :style="{
            opacity: isDeleting || listLoading ? 0.6 : 1,
            pointerEvents: isDeleting || listLoading ? 'none' : 'auto',
          }">
          {{ isDeleting && waitDeleteIndex === index ? "删除中..." : "删除" }}
        </view>

        <!-- 银行卡主体：加载中/删除中禁止交互 -->
        <view
          class="bank-card"
          :style="[
            {
              backgroundColor: card.bgColor,
              transform: `translateX(${card.swipeX}rpx)`,
              opacity: isDeleting && waitDeleteIndex === index ? 0.8 : 1,
            },
            swipeTransition,
          ]"
          @touchstart="handleTouchStart($event, index)"
          @touchmove="handleTouchMove($event, index)"
          @touchend="handleTouchEnd($event, index)"
          @click="handleCardClick(index)"
          :class="{ 'card-disabled': isDeleting || listLoading }">
          <!-- 卡片信息（开户行/卡号/公司名称） -->
          <view class="card-info">
            <view
              class="bank-name"
              :style="{ fontSize: `${bankNameFontSize}rpx` }">
              {{ card.hospitalDeposit }}
            </view>
            <view
              class="card-number"
              :style="{ letterSpacing: `${cardNumberLetterSpacing}rpx` }">
              <text
                v-for="(num, i) in formatCardNumber(card.hospitalNumber)"
                :key="i">
                {{ num }}
              </text>
            </view>
            <view
              class="card-holder"
              :style="{ fontSize: `${holderFontSize}rpx` }">
              {{ card.hospitalCompany }}（尾号{{
                card.hospitalNumber.slice(-4)
              }}）| 行号：{{ card.hospitalBankCode.slice(-4) }}
            </view>
          </view>

          <!-- 卡片类型标签 -->
          <view
            class="card-type"
            :class="{ 'credit-tag': card.type === 'credit' }">
            {{ card.type === "debit" ? "储蓄卡" : "信用卡" }}
          </view>
        </view>
      </view>
    </view>

    <!-- 添加银行卡按钮：加载中/删除中禁用 -->
    <view
      class="add-card-btn"
      @click="navigateToAddCard"
      :style="{
        opacity: isDeleting || listLoading ? 0.6 : 1,
        pointerEvents: isDeleting || listLoading ? 'none' : 'auto',
      }">
      <view class="add-icon">+</view>
      <text class="add-text">添加银行卡</text>
    </view>
  </view>
</template>

<script>
// 移除uni-icons引入：删除import uniIcons和components注册
import * as nurseInfo from "../../common/api/nurseInfo.js";

export default {
  // 移除uni-icons组件注册
  data() {
    return {
      cardList: [],
      safeAreaBottom: 0,
      bankNameFontSize: 32,
      holderFontSize: 26,
      cardNumberLetterSpacing: 2,
      deleteBtnWidth: 160,
      cardItemHeight: 240,
      waitDeleteIndex: -1,
      isDeleting: false, // 删除加载状态
      listLoading: true, // 列表整体加载状态（解决刷新时空白）
      swipeTransition: {
        transition: "transform 0.2s ease, opacity 0.2s ease", // 新增透明度过渡
      },
      uid: "",
    };
  },
  onLoad() {
    this.getSystemInfo();
    this.getList(); // 初始加载列表
  },
  // 新增生命周期：每次页面显示时触发（关键修改）
  onShow() {
    // 页面显示时重新获取列表，确保数据最新
    this.getList();
  },
  methods: {
    // 1. 获取银行卡列表：新增listLoading控制，避免刷新时空白
    getList() {
      this.listLoading = true; // 开始加载，显示加载提示
      const dataJson = uni.getStorageSync("user_info") || "{}";
      const data = JSON.parse(dataJson) || {};
      const param = {
        uid: data.nurseUid,
      };

      nurseInfo
        .queryByBankId(param)
        .then((result) => {
          console.log("接口返回银行卡数据：", result);
          if (result.data.data && Array.isArray(result.data.data)) {
            // 给每个卡片补充滑动默认值，避免状态异常
            this.cardList = result.data.data.map((card) => ({
              ...card,
              swipeX: 0, // 强制复位滑动状态
              startX: 0,
              isMoving: false,
              bgColor: card.bgColor || "#1677FF",
              bankLogo: card.bankLogo || "https://picsum.photos/id/237/40/40",
            }));
          } else {
            this.cardList = []; // 无数据时置空
          }
        })
        .catch((error) => {
          console.log("获取银行卡列表失败：", error);
          uni.showToast({ title: "加载银行卡失败", icon: "none" });
          this.cardList = [];
        })
        .finally(() => {
          this.listLoading = false; // 结束加载，隐藏加载提示
        });
    },

    // 2. 删除逻辑：核心优化——先复位卡片，再刷新列表
    confirmDelete() {
      if (this.waitDeleteIndex === -1 || this.isDeleting) return;

      // 步骤1：锁定状态，禁用所有交互
      this.isDeleting = true;
      const deleteCard = this.cardList[this.waitDeleteIndex];
      console.log("待删除银行卡ID：", deleteCard.id);

      // 步骤2：强制复位当前卡片（关键！避免滑动状态残留）
      deleteCard.swipeX = 0;

      // 步骤3：调用删除接口
      nurseInfo
        .deleteByBankId({ id: deleteCard.id })
        .then((result) => {
          console.log("删除接口返回结果：", result);
          // 接口成功判断（根据实际接口调整）
          if (result.data.code === 200 || result.data.success) {
            uni.showToast({ title: "银行卡删除成功", icon: "success" });
            // 延迟刷新列表（给复位动画留时间，避免视觉跳动）
            setTimeout(() => {
              this.getList();
            }, 200);
          } else {
            uni.showToast({
              title: result.data.msg || "删除失败",
              icon: "none",
            });
          }
        })
        .catch((error) => {
          console.error("删除接口调用失败：", error);
          uni.showToast({ title: "网络异常，删除失败", icon: "none" });
        })
        .finally(() => {
          // 步骤4：解锁状态，恢复交互
          this.isDeleting = false;
          this.waitDeleteIndex = -1;
        });
    },

    // 3. 滑动相关逻辑：新增加载状态判断，禁止加载中滑动
    handleTouchStart(e, index) {
      if (this.isDeleting || this.listLoading) return;
      const card = this.cardList[index];
      card.startX =
        e.touches[0].clientX * (750 / uni.getSystemInfoSync().screenWidth);
      card.isMoving = true;

      // 其他卡片强制复位（避免多卡片同时滑动）
      this.cardList.forEach((item, i) => {
        if (i !== index && item.swipeX !== 0) {
          item.swipeX = 0;
        }
      });
    },

    handleTouchMove(e, index) {
      if (this.isDeleting || this.listLoading || !this.cardList[index].isMoving)
        return;
      const card = this.cardList[index];
      const currentX =
        e.touches[0].clientX * (750 / uni.getSystemInfoSync().screenWidth);
      let swipeX = currentX - card.startX;

      // 边界控制：避免过度滑动
      if (swipeX > 0) swipeX = 0;
      if (swipeX < -this.deleteBtnWidth) swipeX = -this.deleteBtnWidth;

      card.swipeX = swipeX;
    },

    handleTouchEnd(e, index) {
      if (this.isDeleting || this.listLoading) return;
      const card = this.cardList[index];
      card.isMoving = false;

      // 滑动阈值判断：不足一半则复位
      const threshold = -this.deleteBtnWidth / 2;
      if (card.swipeX < threshold) {
        card.swipeX = -this.deleteBtnWidth;
      } else {
        card.swipeX = 0;
      }
    },

    // 4. 点击卡片：加载中/删除中禁止操作
    handleCardClick(index) {
      if (this.isDeleting || this.listLoading) return;
      const card = this.cardList[index];
      if (card.swipeX !== 0) {
        card.swipeX = 0; // 点击展开的卡片，强制复位
      } else {
        // 复制卡号逻辑
        const pureNumber = card.hospitalNumber.replace(/\s/g, "");
        uni.setClipboardData({
          data: pureNumber,
          success: () => uni.showToast({ title: "卡号已复制", icon: "none" }),
          fail: () =>
            uni.showToast({ title: "复制失败，请重试", icon: "none" }),
        });
      }
    },

    // 5. 其他原有方法（删除弹窗、设备信息、跳转）
    handleDelete(index) {
      if (this.isDeleting || this.listLoading) return;
      this.waitDeleteIndex = index;
      uni.showModal({
        title: "确认删除",
        content: "删除后将无法使用该卡进行支付和提现，且不可恢复",
        confirmText: "确认删除",
        cancelText: "取消",
        confirmColor: "#ff3b30",
        success: (res) => {
          if (res.confirm) {
            this.confirmDelete();
          }
          this.waitDeleteIndex = -1;
        },
      });
    },

    getSystemInfo() {
      uni.getSystemInfo({
        success: (res) => {
          this.safeAreaBottom = res.safeAreaInsets?.bottom || 0;
          const screenWidth = res.screenWidth;

          if (screenWidth < 375) {
            this.bankNameFontSize = 28;
            this.holderFontSize = 24;
            this.cardNumberLetterSpacing = 1;
            this.cardItemHeight = 220;
          } else if (screenWidth > 428) {
            this.bankNameFontSize = 34;
            this.holderFontSize = 28;
            this.cardNumberLetterSpacing = 3;
            this.cardItemHeight = 260;
          }
        },
      });
    },

    navigateToAddCard() {
      if (this.isDeleting || this.listLoading) return;
      uni.navigateTo({
        url: "/pages/addCard/addCard",
        fail: () => uni.showToast({ title: "跳转失败，请重试", icon: "none" }),
      });
    },

    formatCardNumber(number) {
      if (!number) return "";
      const pureNumber = number.replace(/\s/g, "");
      return pureNumber.replace(/(\d{4})(?=\d)/g, "$1 ");
    },
  },
};
</script>

<style scoped>
/* 基础容器样式 */
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 顶部提示栏 */
.tip-bar {
  padding: 20rpx 30rpx;
  background-color: #fff8e6;
  border-bottom: 1px solid #ffe8b3;
  box-sizing: border-box;
}
.tip-text {
  font-size: 26rpx;
  color: #ff9800;
  display: block;
  text-align: center;
  white-space: normal;
}

/* 卡片列表容器：新增加载/空列表样式 */
.card-list {
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  gap: 15rpx;
  box-sizing: border-box;
}

/* 列表加载中：居中显示 + 原生CSS动画 */
.list-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15rpx;
  padding: 50rpx 0;
}
/* 原生加载动画：旋转圆圈（替代uni-icons） */
.loading-spinner {
  width: 36rpx;
  height: 36rpx;
  border: 4rpx solid rgba(153, 153, 153, 0.2);
  border-top-color: #999; /* 旋转时的高亮色 */
  border-radius: 50%;
  animation: spin 1s linear infinite; /* 旋转动画 */
}
/* 旋转动画关键帧 */
@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
.loading-text {
  font-size: 28rpx;
  color: #999;
}

/* 空列表提示：居中显示，引导添加 */
.empty-list {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 20rpx;
  padding: 50rpx 0;
}
.empty-img {
  width: 120rpx;
  height: 120rpx;
  opacity: 0.6;
}
.empty-text {
  font-size: 28rpx;
  color: #999;
}
.empty-btn {
  margin-top: 20rpx;
  padding: 15rpx 40rpx;
  background-color: #169bd5;
  color: #fff;
  font-size: 26rpx;
  border-radius: 40rpx;
}

/* 左滑容器：固定高度，避免布局跳动 */
.swipe-container {
  position: relative;
  overflow: hidden;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.05);
  background-color: #fff; /* 兜底背景，避免透明 */
}

/* 删除按钮 */
.delete-btn {
  position: absolute;
  top: 0;
  right: 0;
  width: v-bind(deleteBtnWidth + "rpx");
  height: 100%;
  background-color: #ff3b30;
  color: #ffffff;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1;
  transition: opacity 0.2s;
}

/* 银行卡主体：新增禁用样式 */
.bank-card {
  width: 100%;
  height: 100%;
  padding: 30rpx 25rpx;
  color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  position: relative;
  z-index: 2;
  box-sizing: border-box;
}
.bank-card:active {
  opacity: 0.95;
}
/* 禁用状态：防止误触 */
.card-disabled {
  pointer-events: none !important;
}

/* 银行logo */
.bank-logo {
  width: 60rpx;
  height: 60rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
}
.bank-logo image {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 5rpx;
  box-sizing: border-box;
}

/* 卡片信息 */
.card-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
  min-width: 0;
}
.bank-name {
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.card-number {
  font-size: 36rpx;
  margin-top: 5rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.card-holder {
  opacity: 0.9;
  margin-top: 5rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 24rpx;
}

/* 卡片类型标签 */
.card-type {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  background-color: rgba(255, 255, 255, 0.2);
  flex-shrink: 0;
  margin-left: 15rpx;
}
.credit-tag {
  background-color: rgba(255, 215, 0, 0.8);
  color: #333;
}

/* 添加银行卡按钮 */
.add-card-btn {
  position: fixed;
  bottom: 30rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 90%;
  height: 90rpx;
  background-color: #ffffff;
  border: 2rpx dashed #ccc;
  border-radius: 45rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15rpx;
  font-size: 32rpx;
  color: #666;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  box-sizing: border-box;
  z-index: 99;
  transition: opacity 0.2s;
}
.add-icon {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background-color: #eee;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  line-height: 40rpx;
  flex-shrink: 0;
}

/* 响应式适配 */
@media (max-width: 320px) {
  .bank-card {
    padding: 25rpx 20rpx;
  }
  .card-number {
    font-size: 32rpx;
  }
  .card-holder {
    font-size: 22rpx;
  }
  .list-loading,
  .empty-list {
    padding: 30rpx 0;
  }
  .loading-spinner {
    width: 32rpx;
    height: 32rpx;
  }
}

@media (min-width: 768px) {
  .card-list {
    padding: 40rpx 30rpx;
    gap: 30rpx;
  }
  .bank-card {
    padding: 40rpx 35rpx;
  }
  .bank-logo {
    width: 80rpx;
    height: 80rpx;
  }
  .card-holder {
    font-size: 26rpx;
  }
  .add-card-btn {
    height: 120rpx;
    font-size: 36rpx;
    border-radius: 60rpx;
  }
  .loading-spinner {
    width: 40rpx;
    height: 40rpx;
  }
}
</style>
